﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Ecommerce.Model;
using Ecommerce.Admin.Models;
using Ecommerce.Lib;
using Ecommerce.Lib.Paging;
using System.Web.Security;
using Ecommerce.Lib.Helpers;
using Ecommerce.Lib.Common;
using Ecommerce.Admin.Properties;

namespace Ecommerce.Admin.Controllers
{
    public class ArticleController : Controller
    {
        private ArticleViewModel a = new ArticleViewModel();
        private ArticleCategoryDataModel ac = new ArticleCategoryDataModel();
        private TMDTDataContext db = new TMDTDataContext();
       // [Authorize]
        public ActionResult Index(int? page)
        {
            if (!page.HasValue) page = 1;
            int pageSize = int.Parse(UserState.getUserStateFromRequest("product.pageSize", "PageSize", 10).ToString());
            a.Articles = db.Articles.OrderByDescending(d => d.ID).ToPagedList(page.Value - 1, pageSize);
            a.Filters = Utils.Utils.GetCharToFilter();
            //số sản phẩm trên 1 trang
            ViewData["RecordInPage"] = a.Articles.Count;
            ViewData["TotalRecord"] = db.Articles.ToList().Count;
            return View(a);
        }
       // [Authorize]
        [ValidateInput(false)]
        public ActionResult Filter(string id, int? page)
        {
            if (string.IsNullOrEmpty(id)) id = "";
            if (!page.HasValue) page = 1;
            int pageSize = int.Parse(UserState.getUserStateFromRequest("product.pageSize", "PageSize", 10).ToString());
            a.Filters = Utils.Utils.GetCharToFilter();
            a.Articles = db.Articles.Where(d => d.Title.StartsWith(id)).ToPagedList(page.Value - 1, pageSize);
            ViewData["RecordInPage"] = a.Articles.Count;
            ViewData["TotalRecord"] = a.Articles.TotalItemCount;
            return View("Index", a);
        }
       // [Authorize]
        [ValidateInput(false)]
        public ActionResult Search(string id, int? page)
        {
            if (string.IsNullOrEmpty(id)) id = "";
            if (!page.HasValue) page = 1;
            int pageSize = int.Parse(UserState.getUserStateFromRequest("product.pageSize", "PageSize", 10).ToString());
            a.Filters = Utils.Utils.GetCharToFilter();
            a.Articles = db.Articles.Where(d => d.Title.Contains(id)).ToPagedList(page.Value - 1, pageSize);
            ViewData["txtSearch"] = id;
            ViewData["RecordInPage"] = a.Articles.Count;
            ViewData["TotalRecord"] = a.Articles.TotalItemCount;
            return View("Index", a);
        }
        static bool submit = false;
       // [Authorize]
        public ActionResult Create()
        {
            var categories = db.ArticleCategories.ToList();
            a.Categories = ac.MenuTree(0, categories, 0);
            ViewData["Notice"] = submit == false ? "display:none" : "display:block";
            submit = false;
            return View(a);
        }
       // [Authorize]
        [ValidateInput(false)]
        [HttpPost]
        public ActionResult Create(FormCollection collection)
        {
            //MembershipUser user = Membership.GetUser(User.Identity.Name);
            Article pr = new Article();
            pr.Title = Request.Form["Title"];
            //pr.UserId = (System.Guid)user.ProviderUserKey;
            pr.CategoryID= !string.IsNullOrEmpty(Request.Form["CategoryId"]) ? int.Parse(Request.Form["CategoryId"]) : 0; ;
            pr.Summary = Request.Form["Summary"];
            pr.ArticleContent = Request.Form["ContentDetail"];
            pr.AddDate = DateTime.Now;
            HttpPostedFileBase img = Request.Files["ImagePath"];
            if (!string.IsNullOrEmpty(img.FileName))
            {
                UploadFile.UploadFileToDirectory(img, string.Format("{0}{1}", Settings.Default.SiteRootPath, Settings.Default.ArticleRootPath));
                pr.ImagePath = img.FileName;
            }
            else
            {
                pr.ImagePath = "default.jpg";
            }
            pr.nView = 0;
            pr.Status = bool.Parse(Request.Form["Status"]);
            db.Articles.InsertOnSubmit(pr);
            db.SubmitChanges();
            if (Request.Form["CheckType"].Equals("save_and_back"))
            {
                return RedirectToAction("Index");
            }
            else if (Request.Form["CheckType"].Equals("save_and_check"))
            {
                submit = true;
                return RedirectToAction("Create");
            }
            return RedirectToAction("Index");
        }
        //[Authorize]
        public ActionResult Edit(int? id)
        {
            if (!id.HasValue) return RedirectToAction("Index");
            a.Article = db.Articles.SingleOrDefault(d => d.ID == id);
            var categories = db.ArticleCategories.ToList();
            a.Categories = ac.MenuTree(0, categories, a.Article.CategoryID);
            ViewData["Notice"] = submit == false ? "display:none" : "display:block";
            a.ImagePath = Settings.Default.SiteRootUrl + Settings.Default.ArticleRootUrl;
            submit = false;
            return View(a);
        }
       // [Authorize]
        [ValidateInput(false)]
        [HttpPost]
        public ActionResult Edit(FormCollection collection, int id)
        {
            var pr = db.Articles.SingleOrDefault(d => d.ID == id);
            pr.Title = Request.Form["Title"];
            pr.CategoryID = !string.IsNullOrEmpty(Request.Form["CategoryId"]) ? int.Parse(Request.Form["CategoryId"]) : 0; ;
            pr.Summary = Request.Form["Summary"];
            pr.ArticleContent = Request.Form["ContentDetail"];
            HttpPostedFileBase img = Request.Files["ImagePath"];
            if (!string.IsNullOrEmpty(img.FileName))
            {
                if (!string.IsNullOrEmpty(pr.ImagePath))
                {
                    var mapPath = string.Format("{0}{1}", Settings.Default.SiteRootPath, Settings.Default.ArticleRootPath);
                    System.IO.File.Delete(mapPath + pr.ImagePath);
                }
                UploadFile.UploadFileToDirectory(img, string.Format("{0}{1}", Settings.Default.SiteRootPath, Settings.Default.ArticleRootPath));
                pr.ImagePath = img.FileName;
            }
            //pr.nView = 0;
            pr.Status = bool.Parse(Request.Form["Status"]);
            db.SubmitChanges();
            if (Request.Form["CheckType"].Equals("save_and_back"))
            {
                return RedirectToAction("Index");
            }
            else if (Request.Form["CheckType"].Equals("save_and_check"))
            {
                submit = true;
                return RedirectToAction("Edit");
            }
            return RedirectToAction("Index");
        }
       // [Authorize]
        public ActionResult Delete(int id)
        {
            var del = db.Articles.SingleOrDefault(d => d.ID == id);
            db.Articles.DeleteOnSubmit(del);
            db.SubmitChanges();
            return RedirectToAction("Index");
        }
       // [Authorize]
        public ActionResult ChangeStatus(string id)
        {
            var p = db.Articles.SingleOrDefault(d => d.ID.Equals(id));
            p.Status = p.Status == true ? p.Status = false : p.Status = true;
            db.SubmitChanges();
            string img = p.Status == true ? "<img src='/Content/Images/icon_active.png' style='cursor:pointer' title='Hiển thị' class='changeStatus' id='" + id + "' />" : "<img style='cursor:pointer' title='Không hiển thị' src='/Content/Images/icon_inactive.png' class='changeStatus' id='" + id + "' />";
            return Content(img);
        }
      //  [Authorize]
        public ActionResult DeleteMultiArticle(string id)
        {
            var list = id.Split(';');
            foreach (var item in list)
            {
                var _p = db.Articles.SingleOrDefault(d => d.ID.Equals(item));
                db.Articles.DeleteOnSubmit(_p);
                db.SubmitChanges();
            }
            return Content("true");
        }
        public static IList<SelectListItem> GetStatus()
        {
            var list = new List<SelectListItem>();
            var a = new SelectListItem()
            {
                Value = "false",
                Text = "Không"
            };
            var b = new SelectListItem()
            {
                Value = "true",
                Text = "Có"
            };
            list.Add(a);
            list.Add(b);
            return list;
        }

    }
}
